import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/default_style.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:leader_doctor_flutter/common/utils/date_utils.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/general_dialog_content_widget.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';

// 顶部筛选分类模型
class CommonTimeItemModel {
  String title;
  String titleType;
  bool isSelected;
  String id;

  CommonTimeItemModel({required this.title, required this.titleType, required this.isSelected, required this.id});
}

class MedicalTaskDataStatisticsPage extends StatefulWidget {
  const MedicalTaskDataStatisticsPage({super.key});

  @override
  State<MedicalTaskDataStatisticsPage> createState() => _MedicalTaskDataStatisticsPageState();
}

class _MedicalTaskDataStatisticsPageState extends State<MedicalTaskDataStatisticsPage> {
  final List<CommonTimeItemModel> topFilterItems = [
    CommonTimeItemModel(title: "本月", titleType: "", isSelected: true, id: "0"),
    CommonTimeItemModel(title: "上月", titleType: "", isSelected: false, id: "1"),
    CommonTimeItemModel(title: "近3个月", titleType: "", isSelected: false, id: "2"),
    CommonTimeItemModel(title: "近6个月", titleType: "", isSelected: false, id: "3"),
    CommonTimeItemModel(title: "近12个月", titleType: "", isSelected: false, id: "4"),
  ];

  String startTimeStr = MyDateUtils.getCurrentDate("yyyy-MM");
  String endTimeStr = MyDateUtils.getCurrentDate("yyyy-MM");

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: CommWidget.buildRightBtn(
          "选择时间范围",
          () => {
                _timeSelectorView(),
              }),
    );
  }

  // 时间筛选
  _timeSelectorView() {
    return Container(
      width: double.infinity,
      child: BottomGeneralDialog.showBottomGeneralDialog(
        context,
        title: "选择时间范围",
        desc: "",
        cancelTextColor: ColorRes.colorMain,
        cancelButtonColor: ColorRes.colorEDEDFD,
        cancelBoxDecoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.w),
          border: Border.all(
            color: ColorRes.colorMain,
            width: 1.w,
          ),
          color: ColorRes.colorEDEDFD,
        ),
        confirmButtonColor: ColorRes.colorMain,
        confirmBoxDecoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.w),
          border: Border.all(
            color: ColorRes.colorMain,
            width: 1.w,
          ),
          color: ColorRes.colorMain,
        ),
        descContainer: (c) => Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              _titleView("常用时间"),
              SizedBox(
                height: 12.w,
              ),
              Container(
                width: double.infinity,
                color: Colors.white,
                child: LayoutBuilder(
                  builder: (context, constraints) {
                    return Wrap(
                        spacing: 15.w,
                        runSpacing: 10.w,
                        alignment: WrapAlignment.start,
                        //横轴对齐方式
                        runAlignment: WrapAlignment.end,
                        //纵轴对齐方式
                        children: topFilterItems
                            .map((e) => GestureDetector(
                                  onTap: () {
                                    // int index = topFilterItems.indexWhere(
                                    //     (item) => item.title == e.title);

                                    if (e.id == "0") {
                                      // 当前月e.isSelected = true;
                                      _displayMonthRange(
                                          "当前月份", MyDateUtils.getCurrentMonthStartDate(DateTime.now()), DateTime.now());
                                    } else if (e.id == "1") {
                                      // 上个月
                                      _displayMonthRange("上个月", MyDateUtils.getPreviousMonthFirstDate(DateTime.now()),
                                          MyDateUtils.getPreviousMonthLastDate(DateTime.now()));
                                    } else if (e.id == "2") {
                                      // 近3个月
                                      _displayMonthRange(
                                          "近3个月",
                                          MyDateUtils.getPreviousNMonthsFirstDate(DateTime.now(), 3),
                                          MyDateUtils.getPreviousNMonthsLastDate(DateTime.now(), 1));
                                    } else if (e.id == "3") {
                                      // 近6个月
                                      _displayMonthRange(
                                          "近6个月",
                                          MyDateUtils.getPreviousNMonthsFirstDate(DateTime.now(), 6),
                                          MyDateUtils.getPreviousNMonthsLastDate(DateTime.now(), 1));
                                    } else if (e.id == "4") {
                                      // 近12个月
                                      _displayMonthRange(
                                          "近12个月",
                                          MyDateUtils.getPreviousNMonthsFirstDate(DateTime.now(), 12),
                                          MyDateUtils.getPreviousNMonthsLastDate(DateTime.now(), 1));
                                    }

                                    // 遍历列表，重置所有按钮的 isSelected 为 false
                                    topFilterItems.forEach((item) {
                                      item.isSelected = false;
                                    });
                                    // 设置当前选中项的状态为 true
                                    e.isSelected = true;
                                    (c as Element).markNeedsBuild();
                                  },
                                  child: Container(
                                    height: 30.w,
                                    width: (constraints.maxWidth - 30.w) / 3,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                        color: e.isSelected == true ? ColorRes.color5988fe : ColorRes.colorF5F7FB,
                                        borderRadius: BorderRadius.circular(20.w)),
                                    child: Text(e.title,
                                        style: TextStyle(
                                            color: e.isSelected == true ? Colors.white : ColorRes.color333333,
                                            fontSize: 14.sp)),
                                  ),
                                ))
                            .toList());
                  },
                ),
              ),
              SizedBox(
                height: 18.w,
              ),
              _titleView("自定义时间"),
              SizedBox(
                height: 12.w,
              ),
              Container(
                height: 30.w,
                width: double.infinity,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Expanded(
                      child: _timeButton("${startTimeStr}", "icon_time.webp", () {
                        print("点击了自定义时间 - 开始时间：${startTimeStr}");
                        String startYearStr = _formatDateString(startTimeStr, "yyyy");
                        String startMonthStr = _formatDateString(startTimeStr, "MM");
                        print("endTime = ${startYearStr}, ${startMonthStr}");
                        Pickers.showDatePicker(context,
                            mode: DateMode.YM,
                            selectDate: PDuration(
                              year: int.parse(startYearStr),
                              month: int.parse(startMonthStr),
                            ),
                            minDate: PDuration(year: 2000, month: 1, day: 1),
                            maxDate: PDuration(
                              year: _getCurrentDate("yyyy"),
                              month: _getCurrentDate("MM"),
                              day: _getCurrentDate("dd"),
                            ),
                            pickerStyle: RaisedPickerStyle(haveRadius: true, title: "时间选择", color: ColorRes.colorMain),
                            onConfirm: (p) {
                          String selectTimeStr = "${p.year}-${p.month}";
                          startTimeStr = MyDateUtils.addLeadingZero(selectTimeStr);
                          if (validateDates(startTimeStr, endTimeStr)) {}
                          _refreshBtnStatus(c);
                        });
                      }),
                    ),
                    SizedBox(width: 20.w),
                    Container(
                      width: 15.w,
                      height: 1.w,
                      color: ColorRes.color333333,
                    ),
                    SizedBox(width: 20.w),
                    Expanded(
                      child: _timeButton("${endTimeStr}", "icon_time.webp", () {
                        String endYearStr = _formatDateString(endTimeStr, "yyyy");
                        String endMonthStr = _formatDateString(endTimeStr, "MM");

                        Pickers.showDatePicker(context,
                            mode: DateMode.YM,
                            selectDate: PDuration(
                              year: int.parse(endYearStr),
                              month: int.parse(endMonthStr),
                            ),
                            minDate: PDuration(year: 2000, month: 1, day: 1),
                            maxDate: PDuration(
                              year: _getCurrentDate("yyyy"),
                              month: _getCurrentDate("MM"),
                              day: _getCurrentDate("dd"),
                            ),
                            pickerStyle: RaisedPickerStyle(haveRadius: true, title: "时间选择", color: ColorRes.colorMain),
                            onConfirm: (p) {
                          String selectTimeStr = "${p.year}-${p.month}";
                          endTimeStr = MyDateUtils.addLeadingZero(selectTimeStr);
                          print('结束时间：$selectTimeStr');

                          if (validateDates(startTimeStr, endTimeStr)) {}
                          _refreshBtnStatus(c);
                        });
                      }),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        buttonFontSize: 14.sp,
        onConfirm: () {
          print("确定 开始时间：$startTimeStr, 结束时间：$endTimeStr");

          if (validateDates(startTimeStr, endTimeStr)) {
            context.pop();
          }
        },
        onCancel: () {
          print("取消");
        },
      ),
    );
  }

  /// 遍历列表，重置所有按钮的 isSelected 为 false
  _refreshBtnStatus(BuildContext context) {
    topFilterItems.forEach((item) {
      item.isSelected = false;
    });
    (context as Element).markNeedsBuild();
  }

  // 根据格式返回当前时间对应的年、月、日
  int _getCurrentDate(String format) {
    return int.parse(MyDateUtils.getCurrentDate(format));
  }

  // 根据传入的时间返回对应格式的年、月、日
  _formatDateString(String timeStr, String format) {
    MyDateUtils.formatDateString(startTimeStr, format);
  }

  /// 开始日期和结束日期校验
  bool validateDates(String startYearMonth, String endYearMonth) {
    DateFormat format = DateFormat("yyyy-MM");
    DateTime startDate = format.parse(startYearMonth + "-01");
    DateTime endDate = format.parse(endYearMonth + "-01");

// 如果结束时间早于开始时间，则返回 false
    if (endDate.isBefore(startDate)) {
      Fluttertoast.showToast(msg: "结束日期不能早于开始日期");
      return false;
    }

    // 提取开始时间和结束时间的年份和月份
    int startYear = startDate.year;
    int startMonth = startDate.month;
    int endYear = endDate.year;
    int endMonth = endDate.month;

    // 计算年份差异
    int yearDifference = endYear - startYear;

    // 计算月份差异
    int monthDifference = endMonth - startMonth + 1; // 加1是因为要包含开始月份

    // 如果年份差异大于1，或者年份差异为1且月份差异超过0，则超过12个月
    if (yearDifference > 1 || (yearDifference == 1 && monthDifference > 0)) {
      Fluttertoast.showToast(msg: "起始日期和结束日期的跨度不能超过12个月");
      return false;
    }

    return true;
  }

  _displayMonthRange(String title, DateTime startDate, DateTime endDate) {
    startTimeStr = MyDateUtils.getAtWillFormattedDateTime(startDate, "yyyy-MM");
    endTimeStr = MyDateUtils.getAtWillFormattedDateTime(endDate, "yyyy-MM");

    // String yearStr =
    //     MyDateUtils.timeStringToSpecifiedFormatTimeString(startTimeStr, "yyyy");
    // String monthStr =
    //     MyDateUtils.timeStringToSpecifiedFormatTimeString(startTimeStr, "MM");
    // dayStr = MyDateUtils.getLastDayOfMonthString(
    //     int.parse(yearStr), int.parse(monthStr));

    print('$title:');
    print('开始时间: ${startTimeStr}');
    print('结束时间: ${endTimeStr}');
  }

  Widget _titleView(String? title) {
    return Container(
      child: Text(
        title ?? "",
        style: TextStyle(fontSize: 15.sp, color: ColorRes.color333333, fontWeight: FontWeight.w600),
      ),
    );
  }

  // 显示已选择的时间、自定义时间 的按钮
  Widget _timeButton(String title, String iconStr, VoidCallback onPressed) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ColorRes.colorF5F7FB,
          borderRadius: BorderRadius.circular(20.w),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            ImageLoader.loadAsset(iconStr, 14.w), // 左侧图标
            SizedBox(width: 8), // 图标和文本之间的间距
            Text(
              title,
              style: TextStyle(fontSize: 14.sp, color: ColorRes.color333333),
            ),
          ],
        ),
      ),
    );
  }
}
